<?php
/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2017/1/23
 * Time: 上午12:06
 */

namespace Conf;


use App\Model\Queue;
use App\Model\Runner;
use App\Model\WhPackageTask;
use App\Utility\MyConfInfo;
use App\Utility\SysConst;
use Core\AbstractInterface\AbstractEvent;
use Core\AutoLoader;
use Core\Component\Di;
use Core\Component\Logger;
use Core\Component\ShareMemory;
use Core\Http\Request;
use Core\Http\Response;
use Core\Swoole\AsyncTaskManager;
use Core\Swoole\Timer;


class Event extends AbstractEvent
{
    function frameInitialize()
    {
        // TODO: Implement frameInitialize() method.
        date_default_timezone_set('Asia/Shanghai');
        AutoLoader::getInstance()->requireFile("App/Vendor/Db/MyDb.php");
    }

    function frameInitialized()
    {
        // TODO: Implement frameInitialized() method.
        ShareMemory::getInstance()->clear();
        $conf = Config::getInstance()->getConf('MYSQL');
        Di::getInstance()->set(SysConst::MYSQL, \MyDb::class, array($conf));
        //注入task处理程序
        Di::getInstance()->set('wh', function () {
            return new WhPackageTask();
        });
    }


    function beforeWorkerStart(\swoole_server $server)
    {
        // TODO: Implement beforeWorkerStart() method.
    }

    function onStart(\swoole_server $server)
    {
        // TODO: Implement onStart() method.
    }

    function onShutdown(\swoole_server $server)
    {
        // TODO: Implement onShutdown() method.
    }

    function onWorkerStart(\swoole_server $server, $workerId)
    {
        // TODO: Implement onWorkerStart() method.
        Logger::getInstance('worker_start')->console('workerReloadStart:workerId=>' . $workerId . 'info' . $server->taskworker);
        //为第一个进程添加唤起任务执行的定时器；
        if ($workerId == 0) {
            Timer::loop(1000, function () use ($workerId) {
                $share = ShareMemory::getInstance();
                $taskNum = Queue::getTaskNum();
                $message = 'loop:taskNum=>' . $taskNum;
                if ($taskNum > 0) {
                    //获取系统配置的执行task的数量
                    $runTaskNum = MyConfInfo::getInstance()->getConfig('run_task_num');
                    if (!$runTaskNum) {
                        $runTaskNum = 0;
                    }
                    $message .= ';runTaskNum=>' . $runTaskNum;
                    $curRunTaskNum = $share->get(SysConst::TASK_RUNNING_NUM);
                    $message .= ';curRunTaskNum=>' . $curRunTaskNum;
                    //请勿使得所有worker全部处于繁忙状态   危险操作
                    if ($curRunTaskNum < $runTaskNum) {
                        AsyncTaskManager::getInstance()->add(Runner::class);
                    }
                }
                Logger::getInstance('loop')->console($message);
            });
        }
//        if ($workerId == 1) {
//            Timer::loop(5000, function () use ($workerId) {
//                $taskSwitch = MyConfInfo::getInstance()->getConfig('run_task_switch');
//                if ($taskSwitch) {
//                    $configInfo = MyConfInfo::getInstance()->getConfig('task_info');
//                    if ($configInfo) {
//                        foreach ($configInfo as $key => $val) {
//                            if (Queue::isRunning($val['task_name'])) {  //应该要模糊匹配 不管开启多少个 只要存在一个 就不能进入
//                                continue;
//                            }
//                            //做异步投递
//                            AsyncTaskManager::getInstance()->add(function () use ($val) {
//                                if (Queue::isRunning($val['task_name'])) {  //应该要模糊匹配 不管开启多少个 只要存在一个 就不能进入(因为是一部程序)
//                                    return;
//                                }
//                                //调用配置信息中的 程序获取数据 然后根据thread 来分配多线程任务
//                                $data = array();
//                                if ($val['task_thread'] >= 1) {
//                                    $total = count($data);
//                                }
//                                /*foreach ($configInfo as $key => $val) {
//                                    Queue::setTask($key, serialize($val));
//                                }*/
//                            });
//
//                        }
//
//                    }
//                }
//            });
//        }
    }

    function onWorkerStop(\swoole_server $server, $workerId)
    {
        // TODO: Implement onWorkerStop() method.
    }

    function onRequest(Request $request, Response $response)
    {
        // TODO: Implement onRequest() method.
    }

    function onDispatcher(Request $request, Response $response, $targetControllerClass, $targetAction)
    {
        // TODO: Implement onDispatcher() method.
    }

    function onResponse(Request $request, Response $response)
    {
        // TODO: Implement afterResponse() method.
    }

    function onTask(\swoole_server $server, $taskId, $workerId, $taskObj)
    {
        // TODO: Implement onTask() method.
    }

    function onFinish(\swoole_server $server, $taskId, $taskObj)
    {
        // TODO: Implement onFinish() method.
    }

    function onWorkerError(\swoole_server $server, $worker_id, $worker_pid, $exit_code)
    {
        // TODO: Implement onWorkerError() method.
    }
}
